<?php

/**
 * Session入库工具类
 */
class SessionDB {

    private $_dao;
    private $table_prefix;

    public function __construct()
    {
        //设置SessionDB处理器
        ini_set('session.save_handler', 'user');
        session_set_save_handler(
            array($this, 'userSessionBegin'),
            array($this, 'userSessionEnd'),
            array($this, 'userSessionRead'),
            array($this, 'userSessionWrite'),
            array($this, 'userSessionDelete'),
            array($this, 'userSessionGC')
        );
        $this->table_prefix = $GLOBALS['config']['app']['table_prefix'];
        //开启Session
        session_start();
    }

    function userSessionBegin() {
        //初始化DAO
        $config = $GLOBALS['config']['db'];
        switch ($GLOBALS['config']['app']['dao']) {
            case 'pdo':
                $dao_class = 'MySQLDB';
                break;
            default:
                $dao_class = 'PDODB';
                break;
        }
        $this->_dao = $dao_class::getInstance($config);
    }

    function userSessionEnd() {
        return true;
    }

    /**
     * 读操作
     * 执行时机：session机制开启过程中执行
     * 工作：从当前session数据区读取内容
     * @param string $session_id
     * @return string
     */
    function userSessionRead($session_id) {
        //查询
        $sql = "SELECT session_content FROM `".$this->table_prefix."session` WHERE session_id = '$session_id'";
        return (string)$this->_dao->getOne($sql);
    }

    /**
     * 写操作
     * 执行时机：脚本周期结束时，PHP在整理收尾时
     * 工作：将当前脚本处理好的Session数据，持久化存储到数据库中
     * @param string $session_id
     * @param string $session_content 序列化好的session内容字符串
     * @return bool
     */
    function userSessionWrite($session_id, $session_content) {
        //完成写
        $sql = "REPLACE INTO `".$this->table_prefix."session` VALUES ('$session_id', '$session_content', unix_timestamp())";
        return $this->_dao->query($sql);
    }

    /**
     * 删除操作
     * 执行时机： 调用session_destroy()销毁session过程中被调用
     * 工作：删除当前Session数据区记录
     * @param string $session_id
     * @return bool
     */
    function userSessionDelete($session_id) {
        //删除
        $sql = "DELETE FROM `".$this->table_prefix."session` WHERE session_id = '$session_id'";
        return $this->_dao->query($sql);
    }

    /**
     * 垃圾回收操作
     * 执行时机：开启session机制时有概率的执行
     * 工作： 删除那些过期的Session数据区
     * @param $max_lifetime
     * @return bool
     */
    function userSessionGC($max_lifetime) {
        //删除
        $sql = "DELETE FROM `".$this->table_prefix."session`  WHERE last_time < unix_timestamp()-$max_lifetime";
        return $this->_dao->query($sql);
    }
}